from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from info import db
from info.modules.profile import profile_blu
from utils.common import user_login


# 进入个人中心
@profile_blu.route("/my.html")
@user_login
def my():
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None
    }

    return render_template("users/my.html", errno="0", data=data)


@profile_blu.route("/profile.html")
def profile():
    """个人信息修改界面"""
    return render_template("users/profile.html")


# @profile_blu.route("/api/v1.0/user")
# @user_login
# def return_user_info():
#     """请返回用户信息"""
#     user = g.user
#
#     user_name = request.args.get("name")
#
#     user.name = user_name
#
#     data = {
#         "user_info": user.to_dict()
#     }
#
#     return render_template("users/profile.html", data=data)


@profile_blu.route("/api/v1.0/user/name", methods=["POST"])
@user_login
def profile_info():
    """修改用户名字"""
    user = g.user
    # user_avatar_url = request.json.get("user.avatar_url")
    user_name = request.json.get("name")

    if not all([user_name]):
        return jsonify(errno="4103", errmsg="参数错误")

    user.name = user_name

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno="4001", errmsg="数据库保存失败")
    print(user.name)
    return jsonify(errno="0", errmsg="修改成功")


@profile_blu.route("/orders.html")
def orders():
    data = {}

    return render_template("users/orders.html", data=data)


@profile_blu.route("/auth.html")
def auth():
    data = {}

    return render_template("users/auth.html", data=data)


@profile_blu.route("/myhouse.html")
def myhouse():
    data = {}

    return render_template("users/myhouse.html", data=data)


@profile_blu.route("/lorders.html")
def lorders():
    data = {}

    return render_template("users/lorders.html", data=data)